package org.tlang.ast.list.segment;

import org.tlang.ast.AST;
import org.tlang.ast.ASTList;
import org.tlang.context.ValueTable;
import org.tlang.metaclass.TVar;

import java.util.ArrayList;
import java.util.List;

public class Segment extends ASTList {
    private Segment(List<AST> children) {
        super(children);
    }

    public static AST create(List<AST> children) {
        if (children != null && children.size() == 1) {
            return children.get(0);
        } else {
            return new Segment(children);
        }
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        String div = "";
        for (AST ast : children()) {
            stringBuilder.append(div).append(ast);
            div = "\n";
        }
        return stringBuilder.toString();
    }

    @Override
    public Object eval(ValueTable valueTable) {
        List<Object> ret = new ArrayList<>();
        for (AST ast : children()) {
            Object result = ast.eval(valueTable);
            if (result instanceof TVar) {
                result = ((TVar) result).get();
            }
            ret.add(result);
        }
        return ret;
    }
}
